﻿using MediatR;
using SmartMedicalCare.API.Read.Applications.Commands;
using SmartMedicalCare.Domain;
using SmartMedicalCare.ErronCode;
using SmartMedicalCare.Infrastructure.Implaction;
using SmartMedicalCare.Infrastructure.Migrations;

namespace SmartMedicalCare.API.Read.Applications.CommandHandlers
{
    public class QueryCarouselCommandHandler : IRequestHandler<QueryCarouselCommand, APIResult<APIPaging<CarouselModel>>>
    {
        private readonly IBaseRespository<CarouselModel> carRep;

        public QueryCarouselCommandHandler(IBaseRespository<CarouselModel> carRep)
        {
            this.carRep = carRep;
        }

        public Task<APIResult<APIPaging<CarouselModel>>> Handle(QueryCarouselCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<CarouselModel>> result = new APIResult<APIPaging<CarouselModel>>();
            result.code=ResultCode.显示成功;
            result.Message=ResultCode.显示成功.ToString();
            var res = from a in carRep.GetAll()
                      where a.IsDeleted == false
                      select new CarouselModel
                      {
                          CarouselId=a.CarouselId,
                          Title=a.Title,
                          ImageUrl=a.ImageUrl,
                          JumpUrl=a.JumpUrl,
                          StartTime=a.StartTime,
                          EndTime=a.EndTime,
                          Status=a.Status,
                          CreateTime= a.CreateTime  ,
                          IsDeleted= a.IsDeleted,
                          CreateName=a.CreateName,
                          Counts=a.Counts,
                      };
            //标题模糊查询
            if (!string.IsNullOrEmpty(request.Title))
            {
                res=res.Where(x=>x.Title.Contains(request.Title));
            }
            //时间查询
            if (request.settime!= null && request.enttime != null)
            {
                res=res.Where(x=>x.CreateTime>=request.settime && x.CreateTime<=request.enttime);
            }
            //总条数
            var totalcount=res.Count();
            //总页数
            var totaopage = (int)Math.Ceiling(totalcount * 1.0 / request.Pagsize);
            //排序
            res = res.OrderByDescending(x => x.CarouselId).Skip((request.Pagindex - 1) * request.Pagsize).Take(request.Pagsize);
            APIPaging<CarouselModel> paging = new APIPaging<CarouselModel>();
            paging.totalCount = totalcount;
            paging.totalPage= totaopage;
            paging.Fdata=res.ToList();
            result.Data = paging;

            return Task.FromResult(result);
        }
    }
}
